package com.vue.controller.teacher;

import com.vue.constant.JwtClaimsConstant;
import com.vue.constant.MessageConstant;
import com.vue.context.BaseContext;
import com.vue.dto.*;
import com.vue.exception.PasswordErrorException;
import com.vue.properties.JwtProperties;
import com.vue.result.PageResult;
import com.vue.result.Result;
import com.vue.entity.Teacher;
import com.vue.service.TeacherService;
import com.vue.utils.JwtUtil;

import com.vue.vo.TeacherLoginVO;
import com.vue.vo.TeacherRegisterVO;
import com.vue.vo.UserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RequestMapping("/teacher")
@RestController
@Api(tags = "教师相关接口")
@Slf4j
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/register")
    @ApiOperation("教师注册")
    public Result register(@RequestBody TeacherRegisterVO teacherRegisterVO) {
        log.info("教师注册中：{}", teacherRegisterVO);
        teacherService.register(teacherRegisterVO);
        return Result.success();
    }

    /**
     * 教师登录
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("教师登录")
    public Result<TeacherLoginVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("教师登录：{}", loginDTO);

        Teacher teacher = teacherService.login(loginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.TEACHER_ID, teacher.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getTeacherSecretKey(),
                jwtProperties.getTeacherTtl(),
                claims);

        TeacherLoginVO teacherLoginVO = TeacherLoginVO.builder()
                .id(teacher.getId())
                .username(teacher.getUsername())
                .name(teacher.getName())
                .token(token)
                .isAdmin(teacher.getIsAdmin())
                .isPass(teacher.getIsPass())
                .build();

        return Result.success(teacherLoginVO);
    }

    /**
     * 获取教师信息
     * @return
     */
    @GetMapping("/userInfo")
    @ApiOperation("获取教师信息")
    public Result<UserInfoVO> userInfo() {
        //根据id查询用户
        UserInfoVO userInfoDTO = new UserInfoVO();
        Teacher teacher = teacherService.getUserInfo(userInfoDTO);
        BeanUtils.copyProperties(teacher, userInfoDTO);
        return Result.success(userInfoDTO);
    }

    /**
     * 课程分页查询
     * @param coursePageQueryDTO
     * @return
     */
    @GetMapping("/coursePage")
    @ApiOperation("课程分页查询")
    public Result<PageResult> coursePage(CoursePageQueryDTO coursePageQueryDTO){
        log.info("课程分页查询：{}", coursePageQueryDTO);
        PageResult pageResult = teacherService.coursePageQuery(coursePageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 教师找回密码
     * @param teacherForgetPasswordDTO
     * @return
     */
    @PutMapping("/forgetPassword")
    @ApiOperation("教师找回密码")
    public Result forgetPassword(@RequestBody NewPasswordDTO teacherForgetPasswordDTO){
        log.info("教师找回密码：{}", teacherForgetPasswordDTO);
        teacherService.forgetPassword(teacherForgetPasswordDTO);
        return Result.success();
    }

    /**
     * 教师修改信息
     * @param teacherDTO
     * @return
     */
    @PutMapping("/update")
    @ApiOperation("教师修改信息")
    public Result updateInfo(@RequestBody TeacherDTO teacherDTO) {
        log.info("教师修改信息：{}", teacherDTO);
        teacherService.update(teacherDTO);
        return Result.success();
    }

    /**
     * 教师修改密码
     * @param newPasswordDTO
     * @return
     */
    @PatchMapping("/updatePwd")
    @ApiOperation("教师修改密码")
    public Result updatePwd(@RequestBody NewPasswordDTO newPasswordDTO) {
        log.info("教师修改密码：{}", newPasswordDTO);
        //1.校验参数
        String oldPwd = newPasswordDTO.getOldPassword();
        String newPwd = newPasswordDTO.getNewPassword();
        String rePwd = newPasswordDTO.getRePassword();

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要输入");
        }

        //原密码是否正确
        //调用userService根据用户名拿到原密码，再和old_pwd比对
        Long teacherId = BaseContext.getCurrentId();
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(teacherId);
        Teacher teacher = teacherService.getUserInfo(userInfoVO);
        if (!teacher.getPassword().equals(DigestUtils.md5DigestAsHex(oldPwd.getBytes()))) {
            throw new PasswordErrorException(MessageConstant.OLD_PASSWORD_ERROR);
        }

        //newPwd和rePwd是否一样
        if (!rePwd.equals(newPwd)){
            throw new PasswordErrorException(MessageConstant.NEW_PASSWORD_ERROR);
        }

        if (newPwd.length() < 5 || newPwd.length() > 16) {
            throw new PasswordErrorException(MessageConstant.NEW_PASSWORD_ERROR);
        }

        //2.调用service完成密码更新
        teacherService.updatePwd(newPwd);
        return Result.success();
    }
}
